import json

from flask import request, Blueprint

from api.slider import get_json_response
from api.utils import create_md5, create_token
from exts import db
from models import User

user = Blueprint('user', __name__)


# 登录
@user.route('/login', methods=['POST'])
def login():
    request_dict = json.loads(request.data, encoding='UTF-8')
    username = request_dict.get('username', '')
    password = request_dict.get('password', '')
    password_hash = create_md5(password)
    login_user = User.query.filter(User.username == username, User.password == password_hash).first()
    response_dic = {
         'err': True,
    }
    if login_user:
        token = create_token(login_user.username)
        response_dic['err'] = False
        response_dic['token'] = token.decode("utf-8")
    else:
        response_dic['error'] = '用户名或密码错误!'
    return get_json_response(response_dic, request, is_set_cache=False)


# 注册
@user.route('/register', methods=['POST'])
def register():
    request_dict = json.loads(request.data, encoding='UTF-8')
    username = request_dict.get('username', '')
    password = request_dict.get('password', '')
    response_dic = {
         'err': True,
    }
    if username == '' or password == '':
        response_dic['error'] = '用户名或密码为空!'
        return get_json_response(response_dic, request)
    if len(username) > 100:
        response_dic['error'] = '用户名太长!'
        return get_json_response(response_dic, request)
    if len(password) > 100:
        response_dic['error'] = '密码太长!'
        return get_json_response(response_dic, request)
    register_user = User.query.filter(User.username == username).first()
    if register_user:
        response_dic['error'] = '用户已存在!'
        return get_json_response(response_dic, request)
    register_user = User(username=username, password=create_md5(password))
    db.session.add(register_user)
    db.session.commit()
    response_dic['err'] = False
    return get_json_response(response_dic, request, is_set_cache=False)
